const express = require("express")
const { v4 } = require("uuid")
const jwt = require("jsonwebtoken")
const md5 = require("md5")
const moment = require("moment")
const { query } = require("../db/db")
const getIpAddress = require("../middleware/getIpAddress")
const router = express.Router()
const { secret } = require("../config/config")

router.post("/login", getIpAddress, async (req, res) => {
  console.log(req.body)
  const { username, password, ip } = req.body
  // 查询用户信息
  const sql = `select * from blog_user where username=? and password=?`
  const value = [username, md5(password)]
  const res_search = await query(sql, value)

  // 查询成功后
  if (res_search.code === 200 && res_search.data.length > 0) {
    const { userId, username } = res_search.data[0]
    // 生成token
    const token = jwt.sign({ username, userId }, secret, {
      expiresIn: 60*60*24   // 单位秒
    })

    const sql = `update blog_user set ? WHERE userId = '${userId}'`
    const value = {
      token,
      login_time: moment().format("yyyy-MM-DD HH:mm:ss"),
      ip
    }

    await query(sql, value)

    res.json({
      code: 200,
      msg: "ok",
      data: {
        username,
        userId,
        token,
        loginTime: moment().format("yyyy-MM-DD HH:mm:ss")
      }
    })
  } else {
    res.json({
      code: 500,
      msg: "用户名或密码错误",
      data: null
    })
  }
})

module.exports = router
